<template>
  <div class="finance-income">
    <div class="page-container">
      <!-- 页面标题和日期筛选 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">收入分析</h1>
          <div class="date-filter">
            <a-range-picker
              v-model="dateRange"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
              @change="onDateRangeChange"
              :allowClear="true"
              style="width: 240px; margin-right: 12px"
            />
            <a-button type="primary" @click="refreshData" :loading="loading">
              <a-icon type="reload" />
              刷新数据
            </a-button>
            <a-button @click="exportData" :loading="exportLoading">
              <a-icon type="download" />
              导出数据
            </a-button>
          </div>
        </div>
      </div>

      <!-- 收入概览卡片 -->
      <div class="data-cards-grid">
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 统计期间内的总收入金额 </template>
            <div class="card-title">
              总收入
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value">¥{{ formatNumber(overviewData.totalIncome) }}</div>
            <div class="card-trend">
              <span class="trend-text">较上期</span>
              <span :class="getTrendClass(overviewData.incomeGrowthRate)">
                <a-icon :type="getTrendIcon(overviewData.incomeGrowthRate)" />
                {{ Math.abs(overviewData.incomeGrowthRate) }}%
              </span>
            </div>
          </a-tooltip>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 统计期间内的平均月收入 </template>
            <div class="card-title">
              平均月收入
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value">¥{{ formatNumber(overviewData.avgMonthlyIncome) }}</div>
            <div class="card-trend">
              <span class="trend-text">较上期</span>
              <span :class="getTrendClass(overviewData.avgIncomeGrowthRate)">
                <a-icon :type="getTrendIcon(overviewData.avgIncomeGrowthRate)" />
                {{ Math.abs(overviewData.avgIncomeGrowthRate) }}%
              </span>
            </div>
          </a-tooltip>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 收入增长最高的月份 </template>
            <div class="card-title">
              最高增长月
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value">{{ overviewData.peakMonth }}</div>
            <div class="card-trend">
              <span class="trend-text">增长率</span>
              <span class="trend-positive">
                <a-icon type="arrow-up" />
                {{ overviewData.peakGrowthRate }}%
              </span>
            </div>
          </a-tooltip>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 预计下月收入（基于趋势分析） </template>
            <div class="card-title">
              预计下月收入
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value">¥{{ formatNumber(overviewData.predictedIncome) }}</div>
            <div class="card-trend">
              <span class="trend-text">预测准确率</span>
              <span class="trend-neutral">{{ overviewData.predictionAccuracy }}%</span>
            </div>
          </a-tooltip>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-grid">
        <!-- 月度收入趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">月度收入趋势</h3>
            <div class="chart-controls">
              <a-select v-model="trendPeriod" @change="updateTrendChart" style="width: 120px">
                <a-select-option value="12">近12个月</a-select-option>
                <a-select-option value="6">近6个月</a-select-option>
                <a-select-option value="3">近3个月</a-select-option>
              </a-select>
            </div>
          </div>
          <div class="chart-content">
            <div ref="trendChart" class="chart"></div>
          </div>
        </div>

        <!-- 收入来源分析 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">收入来源分析</h3>
            <div class="chart-controls">
              <a-select v-model="sourceType" @change="updateSourceChart" style="width: 120px">
                <a-select-option value="transaction">交易类型</a-select-option>
                <a-select-option value="customer">客户类型</a-select-option>
              </a-select>
            </div>
          </div>
          <div class="chart-content">
            <div ref="sourceChart" class="chart"></div>
          </div>
        </div>
      </div>

      <!-- 收入增长分析 -->
      <div class="chart-card full-width">
        <div class="chart-header">
          <h3 class="chart-title">收入增长分析</h3>
          <div class="chart-controls">
            <a-select v-model="growthType" @change="updateGrowthChart" style="width: 120px">
              <a-select-option value="month">月度增长</a-select-option>
              <a-select-option value="quarter">季度增长</a-select-option>
              <a-select-option value="year">年度增长</a-select-option>
            </a-select>
          </div>
        </div>
        <div class="chart-content">
          <div ref="growthChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getAction } from '@/api/manage'
import * as XLSX from 'xlsx'

export default {
  name: 'FinanceIncome',
  data() {
    return {
      loading: false,
      exportLoading: false,
      dateRange: [],
      trendPeriod: '12',
      sourceType: 'transaction',
      growthType: 'month',

      // 概览数据
      overviewData: {
        totalIncome: 0,
        avgMonthlyIncome: 0,
        peakMonth: '',
        peakGrowthRate: 0,
        predictedIncome: 0,
        predictionAccuracy: 0,
        incomeGrowthRate: 0,
        avgIncomeGrowthRate: 0,
      },

      // 图表实例
      charts: {
        trend: null,
        source: null,
        growth: null,
      },

      // 图表数据
      chartData: {
        monthlyTrend: [],
        incomeSource: [],
        growthAnalysis: [],
      },
    }
  },

  mounted() {
    this.initCharts()
    this.loadData()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy() {
    Object.values(this.charts).forEach((chart) => {
      if (chart) {
        chart.dispose()
      }
    })
    window.removeEventListener('resize', this.handleResize)
  },

  methods: {
    initCharts() {
      this.$nextTick(() => {
        this.charts.trend = echarts.init(this.$refs.trendChart)
        this.charts.source = echarts.init(this.$refs.sourceChart)
        this.charts.growth = echarts.init(this.$refs.growthChart)
      })
    },

    onDateRangeChange() {
      this.refreshData()
    },

    handleResize() {
      Object.values(this.charts).forEach((chart) => {
        if (chart) {
          chart.resize()
        }
      })
    },

    async refreshData() {
      await this.loadData()
    },

    async loadData() {
      this.loading = true
      try {
        await Promise.all([this.loadOverviewData(), this.loadMonthlyTrend(), this.loadIncomeSource(), this.loadGrowthAnalysis()])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    async loadOverviewData() {
      const params = this.getDateParams()
      const res = await getAction('/statistics/finance/income/overview', params)
      if (res.success && res.result) {
        this.overviewData = {
          totalIncome: res.result.total_income || 0,
          avgMonthlyIncome: res.result.avg_monthly_income || 0,
          peakMonth: res.result.peak_month || '',
          peakGrowthRate: res.result.peak_growth_rate || 0,
          predictedIncome: res.result.predicted_income || 0,
          predictionAccuracy: res.result.prediction_accuracy || 0,
          incomeGrowthRate: res.result.income_growth_rate || 0,
          avgIncomeGrowthRate: res.result.avg_income_growth_rate || 0,
        }
      }
    },

    async loadMonthlyTrend() {
      const params = {
        ...this.getDateParams(),
        period: this.trendPeriod,
      }
      const res = await getAction('/statistics/finance/income/monthly-trend', params)
      if (res.success && res.result) {
        this.chartData.monthlyTrend = res.result
        this.updateTrendChart()
      }
    },

    async loadIncomeSource() {
      const params = {
        ...this.getDateParams(),
        type: this.sourceType,
      }
      const res = await getAction('/statistics/finance/income/source-analysis', params)
      if (res.success && res.result) {
        this.chartData.incomeSource = res.result
        this.updateSourceChart()
      }
    },

    async loadGrowthAnalysis() {
      const params = {
        ...this.getDateParams(),
        type: this.growthType,
      }
      const res = await getAction('/statistics/finance/income/growth-analysis', params)
      if (res.success && res.result) {
        this.chartData.growthAnalysis = res.result
        this.updateGrowthChart()
      }
    },

    updateTrendChart() {
      if (!this.charts.trend) return

      const data = this.chartData.monthlyTrend
      const months = data.map((item) => item.month)
      const income = data.map((item) => item.income || 0)
      const target = data.map((item) => item.target || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['实际收入', '目标收入'],
        },
        xAxis: {
          type: 'category',
          data: months,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => `¥${this.formatNumber(value)}`,
          },
        },
        series: [
          {
            name: '实际收入',
            type: 'line',
            data: income,
            smooth: true,
            itemStyle: {
              color: '#1890ff',
            },
            lineStyle: {
              width: 3,
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(24, 144, 255, 0.3)',
                  },
                  {
                    offset: 1,
                    color: 'rgba(24, 144, 255, 0.1)',
                  },
                ],
              },
            },
          },
          {
            name: '目标收入',
            type: 'line',
            data: target,
            lineStyle: {
              type: 'dashed',
              color: '#52c41a',
              width: 2,
            },
            itemStyle: {
              color: '#52c41a',
            },
          },
        ],
      }

      this.charts.trend.setOption(option)
    },

    updateSourceChart() {
      if (!this.charts.source) return

      const data = this.chartData.incomeSource
      const pieData = data.map((item) => ({
        name: item.source_name,
        value: item.income_amount,
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: ¥{c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '收入来源',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: pieData,
          },
        ],
      }

      this.charts.source.setOption(option)
    },

    updateGrowthChart() {
      if (!this.charts.growth) return

      const data = this.chartData.growthAnalysis
      const periods = data.map((item) => item.period)
      const actualGrowth = data.map((item) => item.actual_growth || 0)
      const expectedGrowth = data.map((item) => item.expected_growth || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['实际增长率', '预期增长率'],
        },
        xAxis: {
          type: 'category',
          data: periods,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%',
          },
        },
        series: [
          {
            name: '实际增长率',
            type: 'bar',
            data: actualGrowth,
            itemStyle: {
              color: (params) => {
                return params.value >= 0 ? '#52c41a' : '#f5222d'
              },
            },
          },
          {
            name: '预期增长率',
            type: 'line',
            data: expectedGrowth,
            itemStyle: {
              color: '#1890ff',
            },
            lineStyle: {
              type: 'dashed',
              width: 2,
            },
          },
        ],
      }

      this.charts.growth.setOption(option)
    },

    getDateParams() {
      const params = {}
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0].format('YYYY-MM-DD')
        params.endDate = this.dateRange[1].format('YYYY-MM-DD')
      }
      return params
    },

    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      }
      return num.toLocaleString()
    },

    getTrendClass(growthRate) {
      if (growthRate > 0) return 'trend-positive'
      if (growthRate < 0) return 'trend-negative'
      return 'trend-neutral'
    },

    getTrendIcon(growthRate) {
      if (growthRate > 0) return 'arrow-up'
      if (growthRate < 0) return 'arrow-down'
      return 'minus'
    },

    async exportData() {
      this.exportLoading = true
      try {
        const exportData = {
          概览数据: this.overviewData,
          月度趋势: this.chartData.monthlyTrend,
          收入来源: this.chartData.incomeSource,
          增长分析: this.chartData.growthAnalysis,
        }

        const wb = XLSX.utils.book_new()

        Object.keys(exportData).forEach((sheetName) => {
          const ws = XLSX.utils.json_to_sheet(Array.isArray(exportData[sheetName]) ? exportData[sheetName] : [exportData[sheetName]])
          XLSX.utils.book_append_sheet(wb, ws, sheetName)
        })

        const fileName = `收入分析统计_${new Date().toISOString().slice(0, 10)}.xlsx`
        XLSX.writeFile(wb, fileName)

        this.$message.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.exportLoading = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.finance-income {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 16px;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #ffffff;
      margin: 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .date-filter {
      display: flex;
      align-items: center;
      gap: 12px;

      .ant-btn-primary {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 8px;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
      }

      .ant-btn:not(.ant-btn-primary) {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        color: #ffffff;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
          border-color: rgba(255, 255, 255, 0.4);
          color: #ffffff;
          transform: translateY(-1px);
        }
      }

      .ant-calendar-picker {
        .ant-calendar-picker-input {
          background: rgba(255, 255, 255, 0.9);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          backdrop-filter: blur(10px);

          &:hover {
            border-color: rgba(255, 255, 255, 0.5);
          }
        }
      }
    }
  }
}

.data-cards-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.data-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.card-trend {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;

  .trend-text {
    color: #909399;
  }

  .trend-positive {
    color: #67c23a;
  }

  .trend-negative {
    color: #f56c6c;
  }

  .trend-neutral {
    color: #909399;
  }
}

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 24px;
}

.chart-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  &.full-width {
    grid-column: 1 / -1;
  }
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-content {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

@media (max-width: 1200px) {
  .data-cards-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .data-cards-grid {
    grid-template-columns: 1fr;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>
